<template>
    <el-container>
        <el-header height="auto" class="jzb-bgheader">
            <div class="u-textinput mr-10" v-if="pageType!=='MY'">
                <div class="inputlabel">省份</div>
                <el-select id="flow-select-regionId" v-model="regionId" size="mini" @change="initComList(true)">
                    <el-option v-for="item in provinceList" :key="item.regionId" :label="item.regionName" :value="item.regionId"></el-option>
                </el-select>
            </div>
            <div class="u-textinput mr-10" v-if="pageType!=='MY'">
                <div class="inputlabel">单位</div>
                <el-select-table :data="comList" keyid="comId" label="comName" memo="systemName" v-model="comId" style="width:220px;"
                    tableWidth="500px" size="mini" @change="queryDataList">
                    <el-table-column slot="column" label="单位名称">
                        <template slot-scope="scope">{{scope.row.comName||scope.row.systemName}}</template>
                    </el-table-column>
                    <myPagination slot="page" @pageChange="initComList(false)" :page="comPage"></myPagination>
                </el-select-table>
            </div>
            <el-input id="flow-input-keyword" placeholder="职位名称关键字" v-model="keyword" size="mini" style="width:250px;" @keyup.enter.native="queryFirstPage">
                <template slot="prepend">关键字</template>
                <i slot="suffix" class="el-input__icon el-icon-search" @click="queryFirstPage" id="flow-search-keyword"></i>
            </el-input>
            <div class="ml-10">
                <button id="flow-btn-add" type="button" class="jzb-button plain" @click="openDrawer('add')"><span class="icon icon-add"></span>新建</button>
                <button id="flow-btn-edit" type="button" class="jzb-button plain" @click="openDrawer('set')"><span class="icon icon-edit"></span>修改</button>
                <button id="flow-btn-remove" type="button" class="jzb-button plain" @click="openDrawer('del')"><span class="icon icon-remove"></span>删除</button>
                <button id="flow-btn-merge" type="button" class="jzb-button plain" @click="openDrawer('merge')"><span class="icon icon-set"></span>融合</button>
            </div>
        </el-header>
        <el-main>
            <el-table id="flow-table-buss" :data="dataList" style="width: 100%;" size="mini" class="jzb-table"
                highlight-current-row  @row-click="rowClick" :cell-class-name="cellClassName" height="calc(100vh - 82px)">
                <el-table-column type="index" class-name="index" width="30" :index="tableIndex"></el-table-column>
                <el-table-column prop="name" label="职位名称" width="150"></el-table-column>
                <el-table-column label="备注" width="200">
                    <template slot-scope="scope">
                        <div class="overflow-ellipsis" v-if="(scope.row.memo+'').length<20">{{scope.row.memo}}</div>
                        <el-tooltip class="item" effect="dark" placement="bottom" v-else>
                            <div slot="content" style="line-height:18px;">
                                <div v-for="(memo,index) in (scope.row.memo+'').split('\n')" :key="'memo'+index">{{memo}}</div>
                            </div>
                            <div class="overflow-ellipsis">{{scope.row.memo}}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="userNum" label="用户数量" align="center" width="100"></el-table-column>
                <el-table-column prop="projMemberNum" label="项目成员数" align="center" width="100"></el-table-column>
                <el-table-column prop="contMemberNum" label="合同成员数" align="center" width="100"></el-table-column>
                <el-table-column prop="enabled" label="状态" width="100" align="center">
                    <template slot-scope="scope">
                        <el-link @click.stop="disableData(scope.row.id)" type="primary" v-if="scope.row.enabled">启用</el-link>
                        <el-link @click.stop="enableData(scope.row.id)" type="danger" v-else>禁用</el-link>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer height="auto">
            <myPagination @pageChange="queryPage" :page="page"></myPagination>
        </el-footer>
        <el-dialog id="flow-dialog-edit" :title="drawertitle" :visible.sync="visibleDrawer" class="jzb-dialog" 
            :close-on-click-modal="false" width="500px" v-dialogDrag>
            <el-form label-position="right" ref="ruleForm" class="ruleForm jzb-form" size="small" :model="ruleForm" :rules="rules" label-width="100px">
                <el-form-item name="name" label="职位名称" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入职位名称" maxlength="20" show-word-limit></el-input>
                </el-form-item>
                <el-form-item name="memo" label="备注" prop="memo">
                    <el-input type="textarea" v-model="ruleForm.memo" placeholder="请输入备注" rows="4" maxlength="100" show-word-limit resize="none"></el-input>
                </el-form-item>
                <el-form-item name="sort" label="排序" prop="sort">
                    <el-input v-model="ruleForm.sort" placeholder="请输入排序" :maxlength="5" @input="ruleForm.sort=(ruleForm.sort+'').replace(/[^\d]/g,'') "></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <button type="button" class="jzb-button" @click="saveFrom('ruleForm')" :disabled="disabledSave"><span class="icon icon-ok"></span>保 存</button>
                <button type="button" class="jzb-button" @click="visibleDrawer = false"><span class="icon icon-undo"></span>取 消</button>
            </div>
        </el-dialog>
        <com-choose-duty @close="dutyVisible=false" :ifInit="false" v-model="mergeDutyList" :visible="dutyVisible" 
            @change="mergeDuty" :exclude="excludeList" :returnValue="true" :title="mergeTitle"></com-choose-duty>
    </el-container>
</template>
<script>
import _ from 'lodash';
import myPagination from "@/components/public/myPagination.vue";
import elSelectTable from "@/components/public/el-select-table.vue";
import comChooseDuty from '@/components/company/com-choose-duty.vue';
import {GetRequestParams} from "@/utils/utils.js";	
import {duty,company} from "@/api/org.js";
export default {
    props:{// 配置项
        pageType:{ type:String, default: 'MY'}, //页面类型 MY-单位职位管理，PART-伙伴，OWN-业主
    },
    components: {
        myPagination,elSelectTable,comChooseDuty,
    },
    data() {
        return {
            row: {}, //选中的行
            keyword:'', //关键字
            userComId:'',
            comId:null, //单位ID
            dataList:[], //数据
            dutyVisible:false,
            page: { pageCurrent: 1, pageSize: 50, total: 0, }, //分页
            comPage: { pageCurrent: 1, pageSize: 50, total: 0, }, //单位分页
            drawertitle: "新建职位", //弹窗标题
            mergeTitle:'选择职位',
            visibleDrawer: false, //弹窗显示
            rules:{
                name: [ { required: true, message: '请输入名称', trigger: 'blur' }],
            },
            mergeDutyList:[],
            ruleForm:{},
            disabledSave:false,
            regionId:'',
            provinceList:null,
            comList:null,
            excludeList:[],
        };
    },
    watch: {
        visibleDrawer(newval) {
            if (newval == false) {
                if (this.$refs.ruleForm) {
                    this.$refs.ruleForm.clearValidate();
                }
                this.initRuleFrom();
            }
        },
        pageType(newval) {
            this.initData()
        },
    },
    mounted() {
        this.userComId = this.$store.state.comId||GetRequestParams().comid;
        this.initData();
    },
    methods:{
        getComId(val){
            this.comId = val;
        },
        async initData(){
            if(this.pageType==='MY'){
                this.comId = this.userComId;
                this.queryDataList();
            }else if(this.pageType==='OWN'){
                const ProvinceList= await company.listOwnProvince({comId:this.userComId});
                this.provinceList = [{"regionId":"all","regionName":"全部"},...ProvinceList.list];
                this.regionId = 'all';
                this.initComList(true);
            }else if(this.pageType==='PART'){
                const ProvinceList= await company.listAgenProvince({comId:this.userComId});
                this.provinceList = [{"regionId":"all","regionName":"全部"},...ProvinceList.list];
                this.regionId = 'all';
                this.initComList(true);
            }
        },
        initComList(flag = false){
            const listurl = (this.pageType==='PART')?company.listAgenPaged:company.listOwnBriefPaged;
            listurl({
                comId:this.userComId,
                regionId:this.regionId,
                page:this.comPage.pageCurrent,
                size:this.comPage.pageSize,
                keywords:''
            }).then(res=>{
                this.comList = res.records;
                this.comPage.total = res.total;
                this.comId = flag && this.comList.length>0?this.comList[0].comId:null;
                if(this.comId){
                    this.queryDataList();
                }else{
                    this.dataList=[];
                }
            });
        },
        //初始化新增form
        initRuleFrom(){
            this.ruleForm={
                enabled:true,
                locked:false,
                name:'',
                memo:'',
                sort:'',
            }
        },
        //1.0 点击一行
        rowClick(val) {
            this.row = val;
        },
        //1.1 分页查询
        queryPage() {
            this.queryDataList();
        },
        //2.2 序号
        tableIndex(number){
            return (this.page.pageCurrent-1)*this.page.pageSize+number+1;
        },
        cellClassName({row, column, rowIndex, columnIndex}){
            let className = column.property?'row'+rowIndex+'-'+column.property:''
            return className;
        },
        //查询第一页
        queryFirstPage(){
            this.page.pageCurrent = 1;
            this.queryDataList();
        },
        //1.2 查询列表
        queryDataList(){
            this.row = {};
            let params={
                comId:this.comId,
                page: this.page.pageCurrent,
                size: this.page.pageSize,
                countUserNum:true,
                countProjMemberNum:true,
                countContMemberNum:true,
                keywords: this.keyword.trim(),
            };
            duty.listPaged(params).then(res=>{
                if (res.code == "30000") {
                    this.dataList = res.records;
                    if(res.records.length==0 && this.page.pageCurrent>1){
                        this.page.pageCurrent-= 1;
                        this.queryDataList();
                    }
                    this.page.total = res.total;
                }else{
                    this.$layer.msg(res.msg);
                }
            })
        },
        //1.3 打开弹窗
        openDrawer(val){
            if(!this.comId){
                this.$layer.msg("请先选择单位");
                return;
            }
            if (val == "add") {
                this.drawertitle = "新建职位";
                this.initRuleFrom();
                this.visibleDrawer = true;
                setTimeout(() => { this.$refs.ruleForm.validate((v)=>{}); }, 100); //默认校验表单
            }
            if (val == "set") {
                if (JSON.stringify(this.row) !== "{}") {
                    this.drawertitle = "修改职位";
                    this.ruleForm = JSON.parse(JSON.stringify(this.row));
                    this.visibleDrawer = true;
                    setTimeout(() => { this.$refs.ruleForm.validate((v)=>{}); }, 100); //默认校验表单
                } else {
                    this.$layer.msg("请选择一条数据");
                    return;
                }
            }
            if (val == "del") {
                if (JSON.stringify(this.row) !== "{}") {
                    if(this.row.userNum||this.row.projMemberNum||this.row.contMemberNum){
                        this.$layer.msg("职位已被使用，不能删除");
                    }else{
                        this.confirmDeleteData();
                    }
                } else {
                    this.$layer.msg("请选择一条数据");
                    return;
                }
            }
            if(val == "merge"){
                if (JSON.stringify(this.row) !== "{}") {
                    this.mergeTitle = `融合职位（注：选中的职务将融合到（${this.row.name}）下）`;
                    this.dutyVisible = true;
                    this.excludeList = [this.row];
                } else {
                    this.$layer.msg("请选择一条数据");
                    return;
                }
            }
        },
        // 1.4 再次确认删除
        confirmDeleteData() {
            this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }) .then(() => {
                this.deleteDataById();
            }) .catch(() => {
                this.$layer.msg("已取消删除");
            });
        },
        // 1.5 删除
        deleteDataById() {
            duty.delete({id:this.row.id,comId:this.comId}).then(res=>{
                this.layerResultTip(res);
            });
        },
        //1.6 保存数据
        saveFrom(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let saveData = this.drawertitle == "新建职位"?duty.create:duty.update;
                    this.ruleForm = _.mapValues(this.ruleForm, (o)=> typeof o==='string'?o.trim():o); //去除字符串值的首尾空格
                    this.disabledSave=true;
                    saveData({...this.ruleForm,comId:this.comId}).then(res=>{
                        this.disabledSave=false;
                        if (res.code == "30000")   this.visibleDrawer = false;
                        this.layerResultTip(res,'保存成功');
                    })
                }
            });
        },
        //2.1 禁用
        disableData(id){
            duty.disable({id:id,comId:this.comId}).then(res=>{
                this.layerResultTip(res,'禁用成功');
            })
        },
        //2.2 启用
        enableData(id){
            duty.enable({id:id,comId:this.comId}).then(res=>{
                this.layerResultTip(res,'启用成功');
            })
        },
        //2.3 职位融合
        mergeDuty(val){
            let mergeDutyList = [...this.excludeList,...val];
            duty.merge({
                comId:this.comId,
                ids:mergeDutyList.map(item=>item.id)
            }).then(res=>{
                this.excludeList = [];
                this.mergeDutyList =[];
                if(res.code == "30000"){
                    this.queryDataList();
                    this.$layer.msg('操作成功');
                }else{
                    this.$layer.msg(res.msg);
                }
            })
        },
        //2.6操作提示
        layerResultTip(res,successTip='操作成功'){
            if (res.code == "30000") {
                this.queryDataList();
                this.$layer.msg(successTip);
            }else{
                this.$layer.msg(res.msg);
            }
        },
    }
};
</script>
<style lang="less" scoped>
@import "~@/assets/style/base.css";
@import "~@/assets/style/common.less";
.el-container{height:calc(100vh - 10px);}
.el-header {padding:5px 10px;display: flex;align-items: center;white-space: nowrap;}
</style>